package concurrent.printAB;

import java.util.concurrent.Semaphore;

/**
 * @author why
 * @data 2021/8/4
 */
public class PrintABSemaphore {
    final static int MAX_PRINT_NUM = 100;
    static volatile int num = 1;
    static Semaphore semaphore = new Semaphore(1);

    public static void printer1() {
        while (num <= MAX_PRINT_NUM) {
            if (num % 2 == 0) {
                boolean b = semaphore.tryAcquire();
                if (!b) {
                    continue;
                }
                System.out.println(num++);
                semaphore.release();
            }

        }
    }

    public static void printer2() {
        while (num <= MAX_PRINT_NUM) {
            if (num % 2 != 0) {
                boolean b = semaphore.tryAcquire();
                if (!b) {
                    continue;
                }
                System.out.println(num++);
                semaphore.release();
            }

        }
    }

    public static void main(String[] args) {
        new Thread(() -> printer1()).start();
        new Thread(() -> printer2()).start();
    }
}
